﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using LmgCMS.Model;
using LmgCMS.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace LmgCMS.Areas.API.Controllers
{
    /// <summary>
    /// GetTreeGridJson
    /// GetGridJson
    /// GetFormJson
    /// SubmitForm
    /// DeleteForm
    /// UpdateField
    /// Switch
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class BaseController<TEntity> : BaseController where TEntity : Entity
    {
        /// <summary>
        /// 身份信息
        /// </summary>
        protected ILoginInfo loginInfo { get; set; }
        protected IDbSession DBA { get; set; }
        protected ISysLogService log { get; set; }
        /// <summary>
        /// cotr
        /// </summary>
        protected BaseController()
        {
            loginInfo = ServiceLocator.Resolve<ILoginInfo>();
            log = ServiceLocator.Resolve<ISysLogService>();
            DBA = DbFactory.DbHelper();
        }
        #region Service
        private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
        /// <summary>
        /// 获取服务。
        /// </summary>
        protected TService Service<TService>() where TService : class
        {
            if (!_services.ContainsKey(typeof(TService)))
            {
                _services[typeof(TService)] = ServiceLocator.Resolve<TService>();
            }
            return (TService)_services[typeof(TService)];
        }
        protected IRepository<TEntity> Repository
        {
            get
            {
                var repo = Service<IRepository<TEntity>>();
                return repo;
            }
        }
        #endregion

        #region CURD
        [HttpGet]
        public virtual IActionResult GetAll(string strWhere = "")
        {
            var data = Repository.FindAll(strWhere);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 获取树形JSON
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public virtual IActionResult GetTreeJson()
        {
            if (EntityHelper.IsTreeEntity(typeof(TEntity)))
            {
                var data = Repository.FindAll().ToList();
                var treeList = new List<TreeViewModel>();
                for (int i = 0; i < data.Count; i++)
                {
                    TEntity item = data[i];
                    TreeEntity treeEntity = item as TreeEntity;
                    TreeViewModel tree = new TreeViewModel();
                    bool hasChildren = Repository.FindAll("ParentID='" + item.ID + "'").ToList().Count == 0 ? false : true;
                    tree.id = item.ID;
                    tree.text = treeEntity.Name;
                    tree.value = item.ID;
                    tree.parentId = treeEntity.ParentID;
                    tree.isexpand = true;
                    tree.complete = true;
                    tree.checkstate = i == 0 ? 1 : 0;
                    tree.hasChildren = hasChildren;
                    treeList.Add(tree);
                }
                return Content(treeList.TreeViewJson());
            }
            else
            {
                return Content("实体类没有继承TreeEntity类");
            }
        }
        /// <summary>
        /// 获取表格树形JSON
        /// </summary>
        [HttpGet]
        public virtual IActionResult GetTreeGridJson(string keyword)
        {
            if (EntityHelper.IsTreeEntity(typeof(TEntity)))
            {
                string whereSql = "";
                if (!string.IsNullOrWhiteSpace(keyword))
                {
                    whereSql = " Name like '%" + keyword + "%'";
                }
                var data = Repository.FindAll(whereSql);
                var treeList = new List<TreeGridModel>();
                foreach (TEntity item in data)
                {
                    TreeEntity treeEntity = item as TreeEntity;
                    TreeGridModel treeModel = new TreeGridModel();
                    bool hasChildren = Repository.FindAll("ParentID='" + item.ID + "'").ToList().Count == 0 ? false : true;
                    treeModel.id = item.ID;
                    treeModel.isLeaf = hasChildren;
                    treeModel.parentId = treeEntity.ParentID;
                    treeModel.expanded = hasChildren;
                    treeModel.entityJson = item.ToJson();
                    treeList.Add(treeModel);
                }
                return Content(treeList.TreeGridJson());
            }
            else
            {
                return Content("实体类没有继承TreeEntity类");
            }
        }
        /// <summary>
        /// 获取表格JSON
        /// </summary>
        [HttpGet]
        public virtual IActionResult GetGridJson(string keyword = "")
        {
            var data = Repository.FindAll(keyword);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 获取表格JSON 带分页
        /// </summary>
        [HttpPost]
        public virtual IActionResult GetJGridPageDataJson([FromBody] Paging paging)
        {
            if (string.IsNullOrWhiteSpace(paging.field)) paging.field = "*";
            if (string.IsNullOrWhiteSpace(paging.sidx)) paging.field = "AddTime";
            if (string.IsNullOrWhiteSpace(paging.sord)) paging.field = "DESC";
            if (paging.page < 0) paging.page = 0;
            if (paging.rows <= 0) paging.rows = 10;

            JQridPageData pageData = Repository.FindAll(paging);
            return Content(pageData.ToJson());
        }
        /// <summary>
        /// 获取表单
        /// </summary>
        [HttpGet]
        public virtual IActionResult GetFormJson(string keyId)
        {
            if (string.IsNullOrWhiteSpace(keyId)) return Error("参数keyId不能为空！");
            var data = Repository.Find(keyId);
            return Content(data.ToJson());
        }
        /// <summary>
        /// 提交表单
        /// </summary>
        [HttpPost]
        public virtual IActionResult SubmitForm([FromBody] TEntity module)
        {
            Repository.AddOrUpdate(module);
            AddLog("提交表单", module.ToJson());
            return Success("提交成功。");
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        [HttpPost]
        public virtual IActionResult DeleteForm(string keyId)
        {
            if (string.IsNullOrWhiteSpace(keyId)) return Error("参数keyId不能为空！");
            Repository.Delete(keyId);
            AddLog("删除数据", keyId);
            return Success("删除成功。");
        }
        /// <summary>
        /// 更新字段
        /// </summary>
        /// <param name="keyId">ID</param>
        /// <param name="fieldName">字段名称</param>
        /// <param name="fieldValue">字段值</param>
        /// <returns></returns>
        [HttpPost]
        public virtual IActionResult UpdateField(string keyId, string fieldName, string fieldValue)
        {
            if (string.IsNullOrWhiteSpace(keyId)) return Error("参数keyId不能为空！");
            if (string.IsNullOrWhiteSpace(fieldName)) return Error("参数fieldName不能为空！");
            if (string.IsNullOrWhiteSpace(fieldValue)) return Error("参数fieldValue不能为空！");

            Repository.UpdateField(keyId, fieldName, fieldValue);
            AddLog("更新字段", fieldName);
            return Success("操作成功。");
        }
        /// <summary>
        /// 更新排序OrderBy
        /// </summary>
        /// <param name="keyId">ID</param>
        /// <param name="value">字段值</param>
        /// <returns></returns>
        [HttpPost]
        public virtual IActionResult UpdateOrderBy(string keyId, string value)
        {
            if (string.IsNullOrWhiteSpace(keyId)) return Error("参数keyId不能为空！");
            if (string.IsNullOrWhiteSpace(value)) return Error("参数value不能为空！");
            Repository.UpdateField(keyId, "OrderBy", value);
            return Success("操作成功。");
        }
        /// <summary>
        /// 开关 Status
        /// </summary>
        [HttpPost]
        public virtual IActionResult Switch(string keyId)
        {
            if (keyId == null) throw new ArgumentNullException(nameof(keyId));
            var model = Repository.Find(keyId);
            if (model != null)
            {
                var obj = model.GetPropertyValue("Status");
                if (obj != null)
                {
                    int Status = (int)obj;
                    if (Status > 0)
                    {
                        Status = 0;
                    }
                    else
                    {
                        Status = 1;
                    }
                    model.SetPropertyValue("Status", Status);
                    Repository.Update(model);
                }
            }
            return Success("操作成功。");
        }
        #endregion


        private void AddLog(string title,string msg)
        {
            log.Add(new SysLog
            {
                ID = UUIDUtils.Fid,
                Application = "CMS",
                Href = typeof(TEntity).GetDescription(),
                TypeId = "",
                TypeName = title,
                Content = msg,
                Status = 0,
                OrderBy = 0,
                Ip = "127.0.0.1",
                Result = 0,
                CreateId = loginInfo.AccountId,
                CreateName = loginInfo.AccountName,
                AddTime = DateTime.Now,
            });
        }
    }
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class BaseController : ControllerBase
    {
        #region Success Error
        protected virtual IActionResult Success(string message = "操作成功")
        {
            return Content(ShowMessage.Success("操作成功"));
        }
        protected virtual IActionResult Success(string message, object data)
        {
            return Content(ShowMessage.Success(message, data));
        }
        protected virtual IActionResult Error(string message = "操作失败")
        {
            return Content(ShowMessage.Error(message));
        }
        /// <summary>
        /// 当前地址
        /// </summary>
        /// <returns></returns>
        protected string GetAbsoluteUri()
        {
            return new StringBuilder()
                .Append(Request.Scheme)
                .Append("://")
                .Append(Request.Host)
                .Append(Request.PathBase)
                .Append(Request.Path)
                .Append(Request.QueryString)
                .ToString();

        }
        /// <summary>
        /// 根地址
        /// </summary>
        /// <returns></returns>
        protected string GetRootUrl()
        {
            return new StringBuilder().Append(Request.Scheme).Append("://").Append(Request.Host).ToString();
        }
        #endregion
    }

}
